package linc.spring.demo;

import linc.spring.demo.bean.User;
import linc.spring.demo.config.ApplicationConfiguration;
import org.junit.Test;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author yqlin
 * @date 2021/9/6 23:02
 * @description BeanDefinition表示Bean定义，BeanDefinition中存在很多属性用来描述一个Bean的特点
 */
public class SpringBeanDefinitionTest {
    /**
     * @BeanDefinition Bean定义信息
     * @class Bean的类型
     * @scope Bean是否是singleton prototype
     * @lazyInit 是否懒加载
     * @initMethodName Bean初始化执行的方法
     * @destoryMethodName Bean销毁的时候执行的方法
     * 等等
     */
    @Test
    public void testBeanDefinition() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
        // 生成一个BeanDefinition对象，并设置beanClass为User.class，并注册到ApplicationContext中
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(User.class).getBeanDefinition();
        applicationContext.registerBeanDefinition("user", beanDefinition);
        // linc.spring.demo.bean.User@6279cee3
        System.out.println(applicationContext.getBean("user"));
        // linc.spring.demo.bean.User@6279cee3
        System.out.println(applicationContext.getBean("user"));
    }

    @Test
    public void testBeanDefinitionByOthersParameter() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
        // 生成一个BeanDefinition对象，并设置beanClass为User.class，并注册到ApplicationContext中
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(User.class).getBeanDefinition();
        beanDefinition.setLazyInit(true);
        beanDefinition.setScope("prototype");
        beanDefinition.setInitMethodName("initMethod");
        beanDefinition.setDestroyMethodName("destroyMethod");
        applicationContext.registerBeanDefinition("user", beanDefinition);
        // linc.spring.demo.bean.User@29ba4338
        System.out.println(applicationContext.getBean("user"));
        // linc.spring.demo.bean.User@29ba4338
        System.out.println(applicationContext.getBean("user"));
    }
}
